<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

$db = Database::getInstance();

// 初始化变量
$userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user = [];
$isEdit = $userId > 0;
$errors = [];

// 如果是编辑模式，获取用户信息
if ($isEdit) {
    $user = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "users WHERE id = ?", [$userId]);
    
    if (!$user) {
        $_SESSION['flash_message'] = '用户不存在';
        $_SESSION['flash_type'] = 'danger';
        header('Location: users.php');
        exit;
    }
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取表单数据
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $confirmPassword = trim($_POST['confirm_password'] ?? '');
    $nickname = trim($_POST['nickname'] ?? '');
    $role = $_POST['role'] ?? 'user';
    $status = $_POST['status'] ?? 'active';
    
    // 验证表单数据
    if (empty($username)) {
        $errors['username'] = '用户名不能为空';
    } elseif (strlen($username) < 3 || strlen($username) > 20) {
        $errors['username'] = '用户名长度应为3-20个字符';
    }
    
    if (empty($email)) {
        $errors['email'] = '邮箱不能为空';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = '邮箱格式不正确';
    }
    
    // 检查用户名和邮箱是否已存在
    $existingSql = "SELECT id FROM " . DB_PREFIX . "users WHERE (username = ? OR email = ?)";
    $existingParams = [$username, $email];
    
    if ($isEdit) {
        $existingSql .= " AND id != ?";
        $existingParams[] = $userId;
    }
    
    $existingUser = $db->fetchRow($existingSql, $existingParams);
    
    if ($existingUser) {
        $existingUsername = $db->fetchRow("SELECT id FROM " . DB_PREFIX . "users WHERE username = ?", [$username]);
        if ($existingUsername && (!$isEdit || $existingUsername['id'] != $userId)) {
            $errors['username'] = '该用户名已被使用';
        }
        
        $existingEmail = $db->fetchRow("SELECT id FROM " . DB_PREFIX . "users WHERE email = ?", [$email]);
        if ($existingEmail && (!$isEdit || $existingEmail['id'] != $userId)) {
            $errors['email'] = '该邮箱已被使用';
        }
    }
    
    // 如果是添加用户或修改密码，则验证密码
    if (!$isEdit || !empty($password)) {
        if (empty($password) && !$isEdit) {
            $errors['password'] = '密码不能为空';
        } elseif (!empty($password) && strlen($password) < 6) {
            $errors['password'] = '密码长度不能少于6个字符';
        } elseif ($password !== $confirmPassword) {
            $errors['confirm_password'] = '两次输入的密码不一致';
        }
    }
    
    // 处理头像上传
    $avatar = $isEdit ? $user['avatar'] : '';
    
    if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
        $result = uploadImage('avatar', '../uploads/avatars/');
        
        if ($result['success']) {
            $avatar = $result['path'];
            
            // 如果是编辑模式且有旧头像，删除旧头像
            if ($isEdit && !empty($user['avatar']) && file_exists('../' . $user['avatar'])) {
                @unlink('../' . $user['avatar']);
            }
        } else {
            $errors['avatar'] = $result['message'];
        }
    }
    
    // 如果没有错误，保存数据
    if (empty($errors)) {
        $userData = [
            'username' => $username,
            'email' => $email,
            'nickname' => $nickname,
            'role' => $role,
            'status' => $status,
            'avatar' => $avatar
        ];
        
        if (!$isEdit || !empty($password)) {
            $userData['password'] = password_hash($password, PASSWORD_DEFAULT);
        }
        
        if ($isEdit) {
            // 更新用户
            $userData['updated_at'] = date('Y-m-d H:i:s');
            $db->update('users', $userData, 'id = ?', [$userId]);
            
            $_SESSION['flash_message'] = '用户信息已更新';
            $_SESSION['flash_type'] = 'success';
        } else {
            // 添加用户
            $userData['created_at'] = date('Y-m-d H:i:s');
            $userData['updated_at'] = date('Y-m-d H:i:s');
            $db->insert('users', $userData);
            
            $_SESSION['flash_message'] = '用户添加成功';
            $_SESSION['flash_type'] = 'success';
        }
        
        header('Location: users.php');
        exit;
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><?php echo $isEdit ? '<i class="bi bi-pencil"></i> 编辑用户' : '<i class="bi bi-person-plus"></i> 添加用户'; ?></h1>
    <a href="users.php" class="btn btn-secondary">
        <i class="bi bi-arrow-left"></i> 返回用户列表
    </a>
</div>

<div class="card mb-4">
    <div class="card-header">
        <?php echo $isEdit ? '编辑用户信息' : '填写用户信息'; ?>
    </div>
    <div class="card-body">
        <form action="" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control <?php echo isset($errors['username']) ? 'is-invalid' : ''; ?>" 
                           id="username" name="username" 
                           value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ($isEdit ? htmlspecialchars($user['username']) : ''); ?>" 
                           required>
                    <?php if (isset($errors['username'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['username']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="email" class="form-label">邮箱 <span class="text-danger">*</span></label>
                    <input type="email" class="form-control <?php echo isset($errors['email']) ? 'is-invalid' : ''; ?>" 
                           id="email" name="email" 
                           value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ($isEdit ? htmlspecialchars($user['email']) : ''); ?>" 
                           required>
                    <?php if (isset($errors['email'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['email']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="password" class="form-label"><?php echo $isEdit ? '密码（留空则不修改）' : '密码 <span class="text-danger">*</span>'; ?></label>
                    <input type="password" class="form-control <?php echo isset($errors['password']) ? 'is-invalid' : ''; ?>" 
                           id="password" name="password" 
                           <?php echo !$isEdit ? 'required' : ''; ?>>
                    <?php if (isset($errors['password'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['password']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="confirm_password" class="form-label"><?php echo $isEdit ? '确认密码（留空则不修改）' : '确认密码 <span class="text-danger">*</span>'; ?></label>
                    <input type="password" class="form-control <?php echo isset($errors['confirm_password']) ? 'is-invalid' : ''; ?>" 
                           id="confirm_password" name="confirm_password" 
                           <?php echo !$isEdit ? 'required' : ''; ?>>
                    <?php if (isset($errors['confirm_password'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['confirm_password']; ?></div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="nickname" class="form-label">昵称</label>
                    <input type="text" class="form-control" id="nickname" name="nickname" 
                           value="<?php echo isset($_POST['nickname']) ? htmlspecialchars($_POST['nickname']) : ($isEdit ? htmlspecialchars($user['nickname']) : ''); ?>">
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="role" class="form-label">角色</label>
                    <select class="form-select" id="role" name="role">
                        <option value="user" <?php echo (isset($_POST['role']) ? $_POST['role'] === 'user' : ($isEdit ? $user['role'] === 'user' : true)) ? 'selected' : ''; ?>>普通用户</option>
                        <option value="admin" <?php echo (isset($_POST['role']) ? $_POST['role'] === 'admin' : ($isEdit ? $user['role'] === 'admin' : false)) ? 'selected' : ''; ?>>管理员</option>
                    </select>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="status" class="form-label">状态</label>
                    <select class="form-select" id="status" name="status">
                        <option value="active" <?php echo (isset($_POST['status']) ? $_POST['status'] === 'active' : ($isEdit ? $user['status'] === 'active' : true)) ? 'selected' : ''; ?>>活跃</option>
                        <option value="inactive" <?php echo (isset($_POST['status']) ? $_POST['status'] === 'inactive' : ($isEdit ? $user['status'] === 'inactive' : false)) ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="avatar" class="form-label">头像</label>
                    <input type="file" class="form-control <?php echo isset($errors['avatar']) ? 'is-invalid' : ''; ?>" 
                           id="avatar" name="avatar" accept="image/*">
                    <?php if (isset($errors['avatar'])): ?>
                        <div class="invalid-feedback"><?php echo $errors['avatar']; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($isEdit && !empty($user['avatar'])): ?>
                        <div class="mt-2">
                            <img src="<?php echo htmlspecialchars($user['avatar']); ?>" alt="当前头像" class="img-thumbnail" style="max-width: 100px;">
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> <?php echo $isEdit ? '保存修改' : '添加用户'; ?>
                </button>
                <a href="users.php" class="btn btn-secondary ms-2">
                    <i class="bi bi-x"></i> 取消
                </a>
            </div>
        </form>
    </div>
</div>

<?php
require_once 'includes/footer.php';
?> 